package cn.chiship.framework.third.biz.wxpub.service.impl;

import cn.chiship.framework.common.service.GlobalCacheService;
import cn.chiship.framework.third.biz.wxpub.service.ThirdWechatTagService;
import cn.chiship.framework.third.core.common.ThirdUtil;
import cn.chiship.framework.third.core.common.WechatUtils;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.exception.ExceptionUtil;
import cn.chiship.sdk.core.id.SnowflakeIdUtil;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.framework.third.biz.wxpub.mapper.ThirdWechatUserMapper;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatUser;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatUserExample;
import cn.chiship.framework.third.biz.wxpub.service.ThirdWechatUserService;
import cn.chiship.sdk.third.service.WxPubService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 微信用户业务接口实现层 2022/6/18
 *
 * @author lijian
 */
@Service
public class ThirdWechatUserServiceImpl extends BaseServiceImpl<ThirdWechatUser, ThirdWechatUserExample>
        implements ThirdWechatUserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ThirdWechatUserServiceImpl.class);

    @Resource
    ThirdWechatUserMapper thirdWechatUserMapper;

    @Resource
    ThirdWechatTagService thirdWechatTagService;

    @Resource
    private GlobalCacheService globalCacheService;

    @Resource
    private WxPubService wxPubService;

    void wxPubServiceConfig() {
        wxPubService.config(globalCacheService.getWeiXinConfigByAppId(ThirdUtil.getAppId())).token();
    }

    @Override
    public BaseResult getByAppIdAndOpenId(String appId, String openId) {
        ThirdWechatUserExample wechatUserExample = new ThirdWechatUserExample();
        wechatUserExample.createCriteria().andAppIdEqualTo(appId).andOpenIdEqualTo(openId);
        List<ThirdWechatUser> wechatUserList = thirdWechatUserMapper.selectByExample(wechatUserExample);
        if (wechatUserList.isEmpty()) {
            return BaseResult.error("暂无数据");
        }

        return BaseResult.ok(wechatUserList.get(0));
    }

    /**
     * 保存微信用户
     *
     * @param wechatUser
     */
    @Override
    public void saveWechatUser(ThirdWechatUser wechatUser) {
        ThirdWechatUserExample wechatUserExample = new ThirdWechatUserExample();
        wechatUserExample.createCriteria().andAppIdEqualTo(wechatUser.getAppId())
                .andOpenIdEqualTo(wechatUser.getOpenId());
        List<ThirdWechatUser> wechatUserList = thirdWechatUserMapper.selectByExample(wechatUserExample);

        if (wechatUserList.isEmpty()) {
            wechatUser.setId(SnowflakeIdUtil.generateStrId());
            wechatUser.setIsDeleted(BaseConstants.NO);
            wechatUser.setGmtCreated(System.currentTimeMillis());
            wechatUser.setGmtModified(System.currentTimeMillis());
            super.insertSelective(wechatUser);
        } else {
            wechatUser = wechatUserList.get(0);
            wechatUser.setUnSubscripeTime(null);
            wechatUser.setIsCancle(BaseConstants.NO);
            super.updateByPrimaryKeySelective(wechatUser);
        }
    }

    @Override
    public BaseResult insertSelectiveBatch(List<ThirdWechatUser> wechatUsers) {
        thirdWechatUserMapper.insertSelectiveBatch(wechatUsers);
        return BaseResult.ok();
    }

    /**
     * 取消关注
     */
    @Override
    public BaseResult updateByPrimaryKeySelective(ThirdWechatUser wechatUser) {
        wxPubServiceConfig();
        if (!StringUtil.isNullOrEmpty(wechatUser.getRemark())) {
            BaseResult baseResult = wxPubService.updateUserRemark(wechatUser.getOpenId(), wechatUser.getRemark());
            if (!baseResult.isSuccess()) {
                return baseResult;
            }
        }
        if (!StringUtil.isNullOrEmpty(wechatUser.getTagIdList())) {
            List<Integer> tagIds = StringUtil.strToListInteger(wechatUser.getTagIdList(), ",");

            String tempTagId = thirdWechatUserMapper.selectByPrimaryKey(wechatUser.getId()).getTagIdList();
            List<Integer> originalTagIds = new ArrayList<>();
            if (!StringUtil.isNullOrEmpty(tempTagId)) {
                originalTagIds = Arrays.asList((JSON.parseArray(tempTagId).stream().toArray(Integer[]::new)));

            }

            // 新增
            List<Integer> notExists = new ArrayList<>(tagIds);
            notExists.removeAll(originalTagIds);

            // 删除
            List<Integer> currentNotExists = new ArrayList<>(originalTagIds);
            currentNotExists.removeAll(tagIds);

            for (Integer tagId : notExists) {
                BaseResult baseResult = wxPubService.memberBatchTag(wechatUser.getOpenId(),
                        StringUtil.getString(tagId));
                if (!baseResult.isSuccess()) {
                    return baseResult;
                }
            }

            for (Integer tagId : currentNotExists) {
                BaseResult baseResult = wxPubService.memberBatchUnTag(wechatUser.getOpenId(),
                        StringUtil.getString(tagId));
                if (!baseResult.isSuccess()) {
                    return BaseResult.error(baseResult.getData());
                }
            }

        }
        BaseResult userResult = wxPubService.getUserInfo(wechatUser.getOpenId());
        if (userResult.isSuccess()) {
            thirdWechatTagService.syncTags();
            JSONObject userJson = (JSONObject) userResult.getData();
            ThirdWechatUser newWechatUser = WechatUtils.convertJsonToWechatUser(userJson);
            newWechatUser.setAppId(wechatUser.getAppId());
            newWechatUser.setId(wechatUser.getId());
            return super.updateByPrimaryKeySelective(newWechatUser);
        }
        return BaseResult.error(userResult.getData());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult syncUser() {
        try {
            wxPubServiceConfig();
            String appKey = wxPubService.getWeiXinConfigModel().getAppKey();
            BaseResult userOpenIdsResult = wxPubService.syncUser();
            if (userOpenIdsResult.isSuccess()) {
                ThirdWechatUserExample wechatUserExample = new ThirdWechatUserExample();
                wechatUserExample.createCriteria().andAppIdEqualTo(appKey);
                List<ThirdWechatUser> wechatUsers = thirdWechatUserMapper.selectByExample(wechatUserExample);
                List<String> currentOpenIds = new ArrayList<>();
                for (ThirdWechatUser wechatUser : wechatUsers) {
                    currentOpenIds.add(wechatUser.getOpenId());
                }
                JSONObject dataJson = (JSONObject) userOpenIdsResult.getData();
                JSONArray openIds = dataJson.getJSONObject("data").getJSONArray("openid");
                String nextOpenId = dataJson.getString("next_openid");
                Integer total = dataJson.getInteger("total");
                Integer count = dataJson.getInteger("count");
                List<String> networkOpenIds = new ArrayList<>();
                for (Integer i = 0; i < openIds.size(); i++) {
                    networkOpenIds.add(openIds.getString(i));
                }

                /**
                 * 删除
                 */
                List<String> currentNotExists = new ArrayList<>(currentOpenIds);
                currentNotExists.removeAll(networkOpenIds);
                if (!currentNotExists.isEmpty()) {
                    System.out.println("删除:" + JSON.toJSONString(currentNotExists));
                }

                /**
                 * 新增
                 */
                List<ThirdWechatUser> newWeChatUsers = new ArrayList<>();
                List<String> notExists = new ArrayList<>(networkOpenIds);
                notExists.removeAll(currentOpenIds);
                if (!notExists.isEmpty()) {
                    for (String s : notExists) {
                        BaseResult userResult = wxPubService.getUserInfo(s);
                        if (userResult.isSuccess()) {
                            JSONObject userJson = (JSONObject) userResult.getData();
                            ThirdWechatUser wechatUser = WechatUtils.convertJsonToWechatUser(userJson);
                            wechatUser.setAppId(appKey);
                            wechatUser.setId(SnowflakeIdUtil.generateStrId());
                            wechatUser.setIsDeleted(BaseConstants.NO);
                            wechatUser.setGmtCreated(System.currentTimeMillis());
                            wechatUser.setGmtModified(System.currentTimeMillis());
                            newWeChatUsers.add(wechatUser);
                        }
                    }
                    thirdWechatUserMapper.insertSelectiveBatch(newWeChatUsers);
                }
                return BaseResult.ok();
            }
            return BaseResult.error(userOpenIdsResult.getData());
        } catch (Exception e) {
            LOGGER.error("系统错误" + e.getLocalizedMessage());
            return ExceptionUtil.formatException(e);
        }
    }


}
